package com.tjcm.tjcminspectmanager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.AsyncWeakTask;
import cn.emagsoftware.util.CodeException;
import cn.emagsoftware.util.LogManager;

import com.tjcm.tjcminspectmanager.manager.NetManager;
import com.tjcm.tjcminspectmanager.model.KeyValue;
import com.tjcm.tjcminspectmanager.model.TaskItem;
import com.tjcm.tjcminspectmanager.model.User;

public class TaskPendingDetailActivity extends BaseActivity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }
        Intent intent = getIntent();
        final TaskItem item = (TaskItem) intent.getSerializableExtra("TASK_ITEM");
        final User user = (User) intent.getSerializableExtra("USER");
        setContentView(R.layout.taskpendingdetail);

        LinearLayout itemWrap = (LinearLayout) findViewById(R.id.item_wrap);
        TextView name = (TextView) findViewById(R.id.name);
        TextView spotname = (TextView) findViewById(R.id.spotname);
        TextView starttime = (TextView) findViewById(R.id.starttime);
        TextView endtime = (TextView) findViewById(R.id.endtime);
        Button begin = (Button) findViewById(R.id.begin);
        Button back = (Button) findViewById(R.id.back);

        name.setText(item.taskName);
        spotname.setText(item.spotName);
        starttime.setText(item.startTime);
        endtime.setText(item.endTime);
        float scale = getResources().getDisplayMetrics().density;
        LinearLayout.LayoutParams keyParams = new LinearLayout.LayoutParams((int) (80 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
        keyParams.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout.LayoutParams valueParams = new LinearLayout.LayoutParams((int) (190 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
        valueParams.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout.LayoutParams wrapParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        wrapParams.gravity = Gravity.CENTER_HORIZONTAL;
        wrapParams.topMargin = (int) (15 * scale + 0.5f);
        String colon = getString(R.string.generic_colon);
        for (KeyValue keyValue : item.keyValues)
        {
            TextView key = new TextView(this);
            key.setText(keyValue.name.endsWith(colon) ? keyValue.name : keyValue.name + colon);
            TextView value = new TextView(this);
            value.setText(keyValue.value);
            LinearLayout wrap = new LinearLayout(this);
            wrap.addView(key, keyParams);
            wrap.addView(value, valueParams);
            itemWrap.addView(wrap, wrapParams);
        }
        begin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                new AsyncWeakTask<String, Object, Object>(TaskPendingDetailActivity.this)
                {
                    protected void onPreExecute(Object[] objs)
                    {
                        ProgressDialog dialog = DialogManager.showProgressDialog((Context) objs[0], R.string.generic_dialog_title, R.string.taskpendingdetail_btn_begin_process, null, null, true,
                                false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
                        {
                            @Override
                            public void onCancel(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                cancel(true);
                            }
                        });
                        addToWeakReference(dialog);
                    }

                    protected Object doInBackgroundImpl(String... arg0) throws Exception
                    {
                        NetManager.startPendingTask(arg0[0], arg0[1]);
                        return null;
                    }

                    protected void onPostExecute(Object[] objs, Object result)
                    {
                        ((ProgressDialog) objs[1]).dismiss();
                        final Activity activity = (Activity) objs[0];
                        DialogManager.showAlertDialog(activity, R.string.generic_dialog_title, R.string.taskpendingdetail_btn_begin_success, new int[] { R.string.generic_dialog_btn_ok }, null, true,
                                false).setOnDismissListener(new DialogInterface.OnDismissListener()
                        {
                            @Override
                            public void onDismiss(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                activity.setResult(100);
                                activity.finish();
                            }
                        });
                    }

                    protected void onException(Object[] objs, Exception e)
                    {
                        LogManager.logE(TaskPendingDetailActivity.class, "start pending task failed.", e);
                        ((ProgressDialog) objs[1]).dismiss();
                        int resId;
                        if (e instanceof CodeException)
                        {
                            CodeException excep = (CodeException) e;
                            if (NetManager.CODE_IO.equals(excep.getCode()))
                                resId = R.string.generic_error_io;
                            else
                                resId = R.string.taskpendingdetail_btn_begin_failed;
                        } else
                        {
                            resId = R.string.generic_error;
                        }
                        DialogManager.showAlertDialog((Context) objs[0], R.string.generic_dialog_title, resId, new int[] { R.string.generic_dialog_btn_ok }, null, true, false);
                    }
                }.execute(user.userId, item.taskId);
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

}